package com.wishwall.helpers;

import java.util.Calendar;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Configuration;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.preference.PreferenceManager;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.util.Log;

import com.wishwall.ws.data.DeviceInformation;

/**
 * Utility class providing methods for getting device information and Device UUID
 *
 * @author georgi.tsankov
 */
public class DeviceInfoHelper {

    private static final String TAG = "DeviceInfo";
    private static final String OS_VERSION_PROPERTY_KEY = "os.version";

    private Context context;

    public DeviceInfoHelper(Context context) {
        this.context = context;
    }

    /**
     * @param context
     * @return {@link DeviceInformation} bean containing useful device properties.
     */
    public DeviceInformation getDeviceInformation() {
        DeviceInformation deviceInformation = new DeviceInformation();
        deviceInformation.setAndroidOSVersion(System.getProperty(OS_VERSION_PROPERTY_KEY));
        try {
            deviceInformation.setApplicationVersion(context.getPackageManager().getPackageInfo(
                            context.getPackageName(), 0).versionName);
        } catch (NameNotFoundException e) {
            Log.w(TAG, "Application package not found! ", e);
        }
        TelephonyManager telephonyManager = (TelephonyManager) context
                        .getSystemService(Context.TELEPHONY_SERVICE);
        String country = "";
        if (telephonyManager.getSimState() == TelephonyManager.SIM_STATE_READY) {
            country = telephonyManager.getSimCountryIso();
        }
        if (country.equals("")) {
            country = telephonyManager.getNetworkCountryIso();
        }
        deviceInformation.setCountry(country);
        deviceInformation.setDeviceModel(Build.MODEL);
        deviceInformation.setDeviceManifacturer(Build.MANUFACTURER);
        deviceInformation.setTimezone(Calendar.getInstance().getTimeZone().getID());
        deviceInformation.setDeviceName(Build.DEVICE);
        deviceInformation.setNotificationID(getNotificationId());
        return deviceInformation;
    }

    /**
     * Returns device UUID.
     *
     * @param context
     * @return device UUID
     */
    public String getUniqueDeviceId() {
        SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
        String deviceId = sharedPrefs.getString(Constants.DEVICE_ID_KEY, "");
        return deviceId;
    }

    private String getNotificationId() {
        SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
        String notificationId = sharedPrefs.getString(Constants.C2DM_REGISTRATION_ID_KEY, "");
        return notificationId;
    }

    /**
     * check if the device have valid internet connection
     *
     * @return true if the device have valid internet connection and false if not
     */
    public boolean haveNetworkConnection(Context context) {
        boolean hasConnection = false;

        ConnectivityManager cm = (ConnectivityManager) context
                        .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo[] netInfo = cm.getAllNetworkInfo();
        for (NetworkInfo ni : netInfo) {
            if (ni.getTypeName().equalsIgnoreCase("WIFI") && ni.isConnectedOrConnecting()) {
                hasConnection = true;
                break;
            }
            if (ni.getTypeName().equalsIgnoreCase("MOBILE") && ni.isConnectedOrConnecting()) {
                hasConnection = true;
                break;
            }
        }
        return hasConnection;
    }

    /**
     * Checks if the device is within the supported ones.
     *
     * @param activity which calls the method
     * @return true if device is within supported screen sizes.
     */
    public boolean isDeviceWidthSupported(Activity activity) {
        DisplayMetrics dm = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
        return dm.densityDpi > DisplayMetrics.DENSITY_MEDIUM
                        && dm.densityDpi <= DisplayMetrics.DENSITY_HIGH;
    }

    /**
     * return if the device is tablet
     *
     * @param context the context of the current activity
     * @return true if the device is tablet false if the device is phone
     */
    public boolean isTablet() {
        boolean xlarge = ((context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == 4);
        boolean large = ((context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_LARGE);
        return (xlarge || large);
    }

    /**
     * Fires register intent which registers the current application for receiving C2DM messages.
     *
     * @param context the context of the current activity
     */
    public void register() {
        Log.d(TAG, "start registration process");
        Intent intent = new Intent(Constants.C2DM_REGISTER);
        intent.putExtra("app", PendingIntent.getBroadcast(context, 0, new Intent(), 0));
        // Sender currently not used
        intent.putExtra("sender", Constants.C2DM_SENDER_ID);
        context.startService(intent);
    }

}
